<template>
  <a-layout-header class="header">
    <div class="logo">
      <img src="./image/demo.gif" alt="">
    </div>
    <a-menu
      theme="dark"
      mode="horizontal"
      :style="{ lineHeight: '64px' }"
    >
      <a-menu-item key="/">
        <router-link to="/">首页</router-link>
      </a-menu-item>
      <a-menu-item key="/admin/user" :style="user.id? {} : {display:'none'}">
        <router-link to="/admin/user">用户管理</router-link>
      </a-menu-item>
      <a-menu-item key="/admin/ebook" :style="user.id? {} : {display:'none'}">
        <router-link to="/admin/ebook">电子书管理</router-link>
      </a-menu-item>
      <a-menu-item key="/admin/category" :style="user.id? {} : {display:'none'}">
        <router-link to="/admin/category">分类管理</router-link>
      </a-menu-item>
      <a-popconfirm
        title="确认退出登录?"
        ok-text="是"
        cancel-text="否"
        @confirm="logout()"
      >
        <a class="login-menu" v-show="user.id">
          <span>注销</span>
        </a>
      </a-popconfirm>
      <a class="login-menu" v-show="user.id">
        <span>嗨：{{user.nickname}}</span>
      </a>
      <a class="login-menu" v-show="!user.id" @click="showLoginModal">
        <span>登录</span>
      </a>
    </a-menu>

    <a-modal
      title="登录"
      v-model:visible="loginModalVisible"
      :confirm-loading="loginModalLoading"
      @ok="login"
    >
      <a-form :model="loginUser" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="用户名">
          <a-input v-model:value="loginUser.loginName" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input v-model:value="loginUser.password" type="password" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout-header>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, onMounted  } from 'vue';
  import axios from 'axios';
  import {Tool} from "@/util/tool";
  import { message } from 'ant-design-vue';
  import store from "@/store";
  import { notification } from 'ant-design-vue';

  declare let hexMd5: any;
  declare let KEY: any;

  export default defineComponent({
    name: 'Header',
    setup () {
      // 登录后保存
      const user = computed(() => store.state.user);

      // 用来登录
      const loginUser = ref({
        loginName: "shunwei",
        password: "123456"
      });
      const loginModalVisible = ref(false);
      const loginModalLoading = ref(false);
      const showLoginModal = () => {
        loginModalVisible.value = true;
      };

      // 登录
      const login = () => {
        let password = loginUser.value.password
        const loginName = loginUser.value.loginName;
        if (loginName === null || loginName === "" || loginName == undefined) {
          message.info("用户名记得输入哇！");
          return;
        } 
        if (password === null || password === "" || password == undefined) {
          message.info("天啦噜，密码你怎么都不输入呢？");
          return;
        } 
        loginModalLoading.value = true;
        password = hexMd5(password + KEY);
        axios.post('/user/login', { loginName, password }).then((response) => {
          loginModalLoading.value = false;
          const data = response.data;
          if (data.success) {
            message.success(data.message);
            loginModalVisible.value = false;
            store.commit("setUser", data.content);
            loginUser.value.loginName = "";
            loginUser.value.password = "";
          } else {
            message.error(data.message);
          }
        });
      };

      // 退出登录
      const logout = () => {
        axios.get('/user/logout/' + user.value.token).then((response) => {
          const data = response.data;
          if (data.success) {
            store.commit("setUser", {});
          } else {
            message.error(data.message);
          }
        });
      };
      let websocket: any;
      let token: any;
      const onMessage = (event: any) => {
        notification['info']({
          message: '收到消息',
          description: event.data,
        });
      };
      const initWebSocket = () => {
        // 连接成功
        websocket.onmessage = onMessage;
      };

      onMounted(() => {
        if ('WebSocket' in window) {
          token = Tool.uuid(10);
          // 连接地址：ws://127.0.0.1:8880/ws/xxx
          websocket = new WebSocket(process.env.VUE_APP_WS_SERVER + '/ws/' + token);
          initWebSocket()
        }
      });
      return {
        loginModalVisible,
        loginModalLoading,
        showLoginModal,
        loginUser,
        login,
        user,
        logout
      }
    }
  });
</script>

<style scoped>
  .logo {
    width: 60px;
    height: 60px;
    float: left;
    margin-left: 10px;
  }
  .logo img {
    display: block;
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
  .login-menu {
    float: right;
    color: white;
    padding-left: 10px;
  }
</style>
